<?php

namespace cf\api\page;

require_once dirname(__FILE__).'/../db.php';

function getTree($parentId=null, $showHidden=false, $maxDepth=0, $path='', $depth=1, &$items=array())
{
	if ($maxDepth && $depth > $maxDepth) {
		return array();
	}
	
	$parentId = getID($parentId);
	
	$q = null;
	\cf\createStaticQuery($q,"
		SELECT id, IFNULL(code,id) AS code, parent_id, name, menu_name, icon, short_txt, link, hidden, sort_order, title, keywords, descr
		FROM cf_page
		WHERE (parent_id=:parentId OR (:parentId IS NULL AND parent_id IS NULL))
			". ($showHidden ? '' : 'AND (hidden IS NULL OR hidden=0)') . "
		ORDER BY sort_order ASC
	");
	$pages = \cf\query2arrays($q,array('parentId'=>$parentId),false,'id');
	foreach ($pages as $id => $page) {
		$item = array( '' => $page );
		$item['']['depth'] = $depth;
		$item['']['path'] = $path.'/'.$page['code'];
		if (!$item['']['link']) {
			$item['']['link'] = $item['']['path'];
		}
		getTree($id, $showHidden, $maxDepth, $item['']['path'], ++$depth, $item);
		$items[$page['menu_name']] = $item;
	}
	return $items;
}

function get($id)
{
	static $q = null;
	\cf\createStaticQuery($q,'
		SELECT id, IFNULL(code,id) AS code, parent_id, name, menu_name, link, title, keywords, descr, icon, hidden, sort_order
		FROM cf_page
		WHERE id=:id
	');
	
	$page = $parent = \cf\query2array($q,array('id'=>getID($id))); 
	$path = $branch = array();
	$depth = 0;

	while (true) {
		$path[] = $parent['code'];
		$branch[] = $parent;
		++$depth;
		if (!$parent['parent_id']) {
			break;
		}
		$parent = get( $parent['parent_id'] );
	}
	
	$page['path'] = '/'.implode('/',array_reverse($path));
	$page['parent'] = count($branch) > 1 ? $branch[1] : null;
	$page['branch'] = array_reverse($branch);
	$page['depth'] = $depth;
	
	return $page;
}

function getText($id)
{
	return \cf\query2var("SELECT txt FROM cf_page WHERE id=:id", array('id'=>getID($id)));
}

function getID($code)
{
	if (is_numeric($code)) {
		return (int)$code;
	}
	
	if (is_null($code)) {		//root page
		return null;
	}

	return \cf\query2var("SELECT id FROM cf_page WHERE code=:code",array('code'=>substr($code, strrpos($code,'/')!==false?strrpos($code,'/')+1:0)));
}

?>